#include "apue.h"
#include <pthread.h>

void* ThreadFunc1(void* arg);
void* ThreadFunc2(void* arg);

int main(void)
{
    int err;
    pthread_t tid1,tid2;
    void* tret; //可以用来获取返回值，由于线程的返回值为void* 
    
    //创建线程
    err = pthread_create(&tid1,NULL,ThreadFunc1,NULL);
    if(err != 0)
    {
        err_exit(err,"Can't Create ThreadFunc1");
    }
    err = pthread_create(&tid2,NULL,ThreadFunc2,NULL);
    if(err != 0)
    {
        err_exit(err,"Can't Create ThreadFunc2");
    }
    
    //阻塞主线程，直到所有的子线程执行完毕
    err = pthread_join(tid1,&tret); //阻塞，并且结果保存在tret指针中
    if(err!=0)
    {
        err_exit(err,"Can't join Thread with Thread 1");
    }
    printf("Thread Function 1 is exit,next we will run Thread 2\n");
    printf("We can got return value from Thread 1: %ld\n",(unsigned long)tret);
    err = pthread_join(tid2,&tret);
    if(err!=0)
    {
        err_exit(err,"Can't join Thread with Thread 1");
    }
    printf("Thread Function is exit,we will close this process\n");
    printf("We can got return value from Thread 2: %ld\n",(unsigned long)tret);
    exit(0);
}

void* ThreadFunc1(void* arg)
{
    printf("Now Thread Function 1 can return\n");
    return((void*)1);
}

void* ThreadFunc2(void* arg)
{
    printf("Now Thread Function can return\n");
    pthread_exit((void*)2);
}